<template>
  <div class="department-chart">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading">
      <div class="spinner"></div>
      <p>正在加载数据...</p>
    </div>

    <!-- 错误状态 -->
    <div v-else-if="error" class="error">
      <i class="fa fa-exclamation-circle"></i>
      <p>{{ error }}</p>
      <button @click="fetchData">重试</button>
    </div>

    <!-- 空数据状态 -->
    <div v-else-if="departments.length === 0" class="empty">
      <i class="fa fa-folder-open-o"></i>
      <p>暂无部门数据</p>
    </div>

    <!-- 柱状图 -->
    <div v-else class="chart-container">
      <div class="chart-title" width="800px">部门人数统计</div>
      <div class="chart-grid">
        <!-- Y轴刻度 -->
        <div class="y-axis">
          <div v-for="tick in yTicks" :key="tick" class="y-tick">
            <span>{{ tick }}</span>
          </div>
        </div>

        <!-- 柱状图主体 -->
        <div class="chart-bars">
          <div 
            v-for="(dept, index) in departments" 
            :key="dept.id" 
            class="bar-wrapper"
          >
            <div 
              class="bar" 
              :style="{ 
                height: `${dept.employeeCount / maxCount * 100}%`,
                backgroundColor: getBarColor(index)
              }"
              @mouseenter="showTooltip(dept, $event)"
              @mouseleave="hideTooltip"
            >
              <div class="bar-value">{{ dept.employeeCount }}</div>
            </div>
            <div class="bar-label">{{ dept.name }}</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 悬浮提示框 -->
    <div v-if="tooltipVisible" class="tooltip" :style="{ top: tooltipTop + 'px', left: tooltipLeft + 'px' }">
      <div class="tooltip-content">
        <div class="tooltip-name">{{ tooltipDept.name }}</div>
        <div class="tooltip-count">{{ tooltipDept.employeeCount }} 人</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'

// 状态管理
const loading = ref(true)
const error = ref(null)
const departments = ref([])
const maxCount = ref(0)
const tooltipVisible = ref(false)
const tooltipDept = ref(null)
const tooltipTop = ref(0)
const tooltipLeft = ref(0)

// Y轴刻度计算
const yTicks = computed(() => {
  if (maxCount.value === 0) return []
  const steps = 5 // 刻度数量
  const stepSize = Math.ceil(maxCount.value / steps)
  return Array.from({ length: steps + 1 }, (_, i) => i * stepSize)
})

// 获取柱状图颜色
const getBarColor = (index) => {
  const colors = ['#36BFFA', '#6EE7B7', '#FDE047', '#FB7185', '#A78BFA']
  return colors[index % colors.length]
}

// 获取部门数据
const fetchData = async () => {
  loading.value = true
  error.value = null
  
  try {
    const response = await fetch('/api/dept')
    
    if (!response.ok) {
      throw new Error(`HTTP错误，状态码: ${response.status}`)
    }
    
    const result = await response.json()
    
    if (result.code !== 200) {
      throw new Error(result.msg || '获取数据失败')
    }
    
    departments.value = result.data || []
    
    // 计算最大值用于比例显示
    maxCount.value = Math.max(
      1, // 防止最大值为0
      ...departments.value.map(dept => dept.employeeCount || 0)
    )
    
    // 添加动画延迟
    setTimeout(() => {
      loading.value = false
    }, 600)
    
  } catch (err) {
    error.value = err.message
    loading.value = false
  }
}

// 生命周期钩子
onMounted(() => {
  fetchData()
})

// 处理提示框显示
const showTooltip = (dept, event) => {
  tooltipDept.value = dept
  tooltipTop.value = event.clientY - 60
  tooltipLeft.value = event.clientX + 10
  tooltipVisible.value = true
}

const hideTooltip = () => {
  tooltipVisible.value = false
}
</script>

<style scoped>
.department-chart {
  width: 100%;
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.loading, .error, .empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
  min-height: 300px;
}

.spinner {
  width: 30px;
  height: 30px;
  border: 3px solid #f3f3f3;
  border-radius: 50%;
  border-top: 3px solid #3498db;
  animation: spin 1s linear infinite;
  margin-bottom: 15px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error {
  color: #e74c3c;
}

.error button {
  margin-top: 15px;
  padding: 8px 15px;
  background-color: #3498db;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.empty {
  color: #95a5a6;
}

.empty i, .error i {
  font-size: 48px;
  margin-bottom: 15px;
}

.chart-title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 20px;
  text-align: center;
}

.chart-grid {
  display: flex;
  height: 300px;
  position: relative;
}

.y-axis {
  width: 50px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding-right: 10px;
  text-align: right;
  color: #7f8c8d;
  font-size: 12px;
}

.y-tick {
  transform: translateY(50%);
}

.chart-bars {
  flex: 1;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(60px, 1fr));
  gap: 10px;
  padding: 0 10px;
  border-left: 1px solid #e5e7eb;
  border-bottom: 1px solid #e5e7eb;
  position: relative;
}

.bar-wrapper {
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
  height: 100%;
}

.bar {
  width: 100%;
  border-radius: 4px 4px 0 0;
  transition: height 0.6s cubic-bezier(0.68, -0.55, 0.27, 1.55);
  position: relative;
  height: 0;
}

.bar-value {
  position: absolute;
  top: -20px;
  left: 50%;
  transform: translateX(-50%);
  font-size: 12px;
  color: #333;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.bar:hover .bar-value {
  opacity: 1;
}

.bar-label {
  margin-top: 10px;
  text-align: center;
  font-size: 12px;
  color: #555;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.tooltip {
  position: fixed;
  z-index: 100;
  pointer-events: none;
}

.tooltip-content {
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 8px 12px;
  border-radius: 4px;
  font-size: 14px;
  min-width: 120px;
  text-align: center;
}

.tooltip-name {
  font-weight: 600;
  margin-bottom: 4px;
}

.tooltip-count {
  font-size: 13px;
}
</style>